<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>hash</title>
  </head>
  <body>
    <div>
      <div class="nav">
        <button data-path="/home">首页</button>
        <button data-path="/center">我的</button>
        <button data-path="/hot">热门</button>
      </div>
      <!-- 路由展示容器 -->
      <div id="view"></div>
    </div>
    <script>
      // 定义路由表
      const routes = [
        { path: "/home", content: "Home" },
        { path: "/center", content: "Center" },
        { path: "/hot", content: "Hot" },
      ];
      // 获取元素
      const oNav = document.querySelector(".nav");
      const oView = document.querySelector("#view");
      // 事件委托绑定路由导航
      oNav.onclick = function (e) {
        if ((e.target.nodeName = "BUTTON")) {
          // 得到导航按钮上的路径属性，并通过 location.hash 修改 hash 路径
          location.hash = e.target.dataset.path;
        }
      };
      // 使用 onhashchange 监听 hash 的变化
      onhashchange = function (e) {
        // newURL: "http://127.0.0.1:5500/20.%E8%B7%AF%E7%94%B1%E5%8E%9F%E7%90%86/hash%E8%B7%AF%E7%94%B1.html#/home"
        const newHash = e.newURL.split("#")[1];
        // 去路由表中查找对应路径的内容，并渲染
        let falg = true
        routes.forEach((route) => {
          const { path, content } = route;
          if (path === newHash) {
            oView.innerHTML = content;
            falg = false
          }
        });
        if (falg) {
          oView.innerHTML = "<h2>404 NotFind</h2>";
        }
      };
    </script>
  </body>
</html>
